package basketball

import (
	"context"
	"encoding/json"
	"github.com/olivere/elastic/v7"
	"longmen/server/config/global"
	"longmen/server/internal/services/nami/services/sports/basketball/bbcache"
)

//从es查1个match
func QueryEsByMatch(matchId int) (*bbcache.LineUp, bool) {
	// query
	q := elastic.NewMatchQuery("line_up.match_id", matchId)
	searchResult, err := global.GetEs().Search().
		Index(bbcache.BasketBallIndexName).
		Query(q).
		From(0).Size(1).
		Do(context.Background())
	if err != nil {
		global.Log.Errorf("lineup query es error: %v", err.Error())
		return nil, false
	}

	// parse
	if searchResult.Hits.TotalHits.Value > 0 {
		wrapper := &EsLineUpWrapper{}
		for _, hit := range searchResult.Hits.Hits {
			err = json.Unmarshal(hit.Source, wrapper)
			if err != nil {
				global.Log.Errorf("lineup query es - parse error: %v", err.Error())
				return nil, false
			}
			return wrapper.LineUp, true
		}
	} else { // not found
		return nil, false
	}

	return nil, false
}

type EsLineUpWrapper struct {
	Type   string          `json:"type"`
	LineUp *bbcache.LineUp `json:"basketball_lineup"`
}
